/*
 * @Author: hongbin
 * @Date: 2021-11-19 22:15:47
 * @LastEditors: hongbin
 * @LastEditTime: 2021-11-21 17:29:35
 * @Description:增加字段 string array 。。。
 */
import { Button, Divider, Input, Typography } from "@mui/material";
import { FC, ReactElement, useRef, useState } from "react";
import { BSONType } from "../../api/types";
import MongodbTypePick from "./MongodbTypePick";
import styled from "styled-components";
import { NoticeRef } from "../Notice";

interface IProps {
  onAdd: (field: any) => any;
  handleClose: () => void;
}

const AddField: FC<IProps> = ({ onAdd, handleClose }): ReactElement => {
  const keyRef = useRef<HTMLInputElement>(null);
  const valueRef = useRef<HTMLInputElement>(null);
  const [type, setType] = useState(BSONType.string);

  const handleAdd = () => {
    const key = keyRef.current!.value;
    const value = valueRef.current!.value;
    if (!key || !value) {
      NoticeRef.current?.open({ message: "填充内容", type: "error" });
      if (!key) keyRef.current?.focus();
      else valueRef.current?.focus();
    } else onAdd({ key, value, type });
  };

  return (
    <Container>
      <Divider />
      <Typography variant="caption">字段名</Typography>
      <Input inputRef={keyRef} />
      <br />
      <br />
      <Typography variant="caption">类型</Typography>
      <MongodbTypePick onChange={setType} />
      <br />
      <br />
      <Typography variant="caption">值</Typography>
      <Input
        multiline
        inputRef={valueRef}
        type={type === BSONType.int ? "number" : "string"}
      />
      <br />
      <br />
      <Typography variant="caption">请输入JSON格式内容</Typography>
      <br />
      <br />
      <Button size="small" variant="outlined" onClick={handleAdd}>
        添加
      </Button>
      <Button size="small" onClick={handleClose}>
        取消
      </Button>
      <Divider />
    </Container>
  );
};

export default AddField;

const Container = styled.div`
  margin: 0.5rem 0;
  display: block !important;
  .MuiTypography-caption {
    min-width: 5rem;
    display: inline-block;
    font-weight: bold;
  }
  button {
    margin: 0.5rem;
  }
`;
